package com.example.controller;

import com.example.data.entity.kg.KgEntity;
import com.example.data.entity.kg.KgRelation;
import com.example.data.vo.Triple;
import com.example.service.TripleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;


@RestController
@RequestMapping("/api/qin-history/triple")
@Api(tags = "三元组接口", description = "用于查询知识图谱三元组数据")
public class TripleController {

    // 直接注入合并后的TripleService（无需改注入方式）
    @Resource
    private TripleService tripleService;

    /**
     * 新增三元组（示例：前端传头实体、关系、尾实体信息）
     */
    @PostMapping("/add")
    @ApiOperation(value = "新增三元组", notes = "传入头实体、关系、尾实体信息，新增完整三元组")
    public ResponseEntity<Map<String, Object>> addTriple(
            @ApiParam(value = "头实体", required = true) @RequestBody KgEntity headEntity,
            @ApiParam(value = "关系", required = true) @RequestBody KgRelation relation,
            @ApiParam(value = "尾实体", required = true) @RequestBody KgEntity tailEntity) {
        Map<String, Object> result = new HashMap<>();
        try {
            Long relationId = tripleService.addTriple(headEntity, relation, tailEntity);
            result.put("success", true);
            result.put("message", "三元组新增成功");
            result.put("relationId", relationId); // 返回关系ID（即三元组标识）
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "三元组新增失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 查询所有有效三元组（原接口，无需修改）
     */
    @GetMapping("/all")
    @ApiOperation(value = "获取所有三元组", notes = "返回知识图谱中所有有效(头实体,关系,尾实体)三元组")
    public ResponseEntity<Map<String, Object>> getAllTriples() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Triple> triples = tripleService.getAllValidTriples();
            result.put("success", true);
            result.put("total", triples.size());
            result.put("triples", triples);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询三元组失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 按头实体ID查询三元组（原接口，无需修改）
     */
    @GetMapping("/by-head")
    @ApiOperation(value = "按头实体查询三元组", notes = "返回指定实体作为头实体的所有三元组")
    public ResponseEntity<Map<String, Object>> getTriplesByHead(
            @ApiParam(value = "头实体ID（kg_entity.id）", required = true, example = "1001")
            @RequestParam Long headEntityId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Triple> triples = tripleService.getTriplesByHeadEntityId(headEntityId);
            result.put("success", true);
            result.put("headEntityId", headEntityId);
            result.put("count", triples.size());
            result.put("triples", triples);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 统计三元组总数（原接口，无需修改）
     */
    @GetMapping("/count")
    @ApiOperation(value = "统计三元组总数", notes = "返回知识图谱中有效三元组的总数量")
    public ResponseEntity<Map<String, Object>> countTriples() {
        Map<String, Object> result = new HashMap<>();
        try {
            int count = tripleService.countValidTriples();
            result.put("success", true);
            result.put("totalTriples", count);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "统计失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 按实体名称查询实体ID（新增接口）
     * 用于前端将实体名称转换为后端需要的startEntityId
     */
    @GetMapping("/entity/queryIdByName")
    @ApiOperation(value = "按名称查询实体ID", notes = "通过实体名称获取对应的ID，支持模糊查询")
    public ResponseEntity<Map<String, Object>> getEntityIdByName(
            @ApiParam(value = "实体名称（支持模糊查询）", required = true, example = "秦始皇")
            @RequestParam(name = "entityName") String entityName) {



        Map<String, Object> result = new HashMap<>();
        try {
            // 调用service层方法查询实体
            List<KgEntity> entities = tripleService.getEntitiesByName(entityName);

            if (entities != null && !entities.isEmpty()) {
                result.put("success", true);
                // 返回匹配的实体列表（包含ID和名称）
                result.put("data", entities.stream().map(entity -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("id", entity.getId());
                    item.put("name", entity.getEntityName());
                    item.put("type", entity.getEntityType());
                    return item;
                }).collect(Collectors.toList()));
            } else {
                result.put("success", false);
                result.put("message", "未找到名称包含【" + entityName + "】的实体");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询实体失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/graph")
    @ApiOperation(value = "获取知识图谱可视化数据", notes = "返回用于图谱展示的节点和关系数据")
    public ResponseEntity<Map<String, Object>> getGraphData(
            @ApiParam(value = "起始实体ID", required = false)
            @RequestParam(name = "startEntityId", required = false) Long startEntityId,
            @ApiParam(value = "展示深度（默认1）", example = "1")
            @RequestParam(name = "depth", defaultValue = "1") Integer depth) {

        Map<String, Object> result = new HashMap<>();
        try {
            // 获取图谱数据（节点+关系）
            Map<String, Object> graphData = tripleService.buildGraphData(startEntityId, depth);
            result.put("success", true);
            result.put("data", graphData);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取图谱数据失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}